package com.kzd.gtgame.base

import android.Manifest
import android.app.Activity
import android.app.Application
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.*
import com.kzd.gtgame.R
import com.kzd.gtgame.app.SPSConstance
import com.kzd.gtgame.entity.*
import com.kzd.gtgame.jetpack.manager.UserRepository
import com.kzd.gtgame.jetpack.manager.getDiskCacheDirectoryApk
import com.kzd.gtgame.utils.httpSign1
import com.kzd.gtgame.utils.httpTime
import com.module.lemlin.http.*
import com.module.lemlin.owner.OwnerApplication
import com.module.lemlin.owner.OwnerViewModel
import com.tbruyelle.rxpermissions3.RxPermissions
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import io.reactivex.rxjava3.functions.Consumer
import rxhttp.wrapper.entity.ProgressT
import java.lang.StringBuilder

open class BaseViewModel(application: Application) : OwnerViewModel(application) {

    override val httpCodeProPer: Int
        get() = 1

    override fun onTokenOverdue() {
//        SPSConstance.clearUser()
//        toAccessActivity()
    }

    private val mUserRepository = UserRepository()

    val userAppUpdateLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<AppUpdate>>>()
    fun userAppUpDate(delay: Long = 0) {
        setRxLifeScope(SubscribeViewModel(userAppUpdateLiveData)) {
            mUserRepository.userAppUpDate(delay)
        }
    }

    val userAppFabLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<HomeFab>>>()
    fun userAppFab() {
        setRxLifeScope(SubscribeViewModel(userAppFabLiveData)) {
            mUserRepository.userAppFab()
        }
    }

    companion object {
        val userAppTipsLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<AppTips>>>()
    }

    fun userAppTips(delay: Long = 0) {
        setRxLifeScope(SubscribeViewModel(userAppTipsLiveData)) {
            mUserRepository.userAppTips(delay)
        }
    }

    val userServiceLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<UserService>>>()
    fun userService() {
        setRxLifeScope(SubscribeViewModel(userServiceLiveData)) {
            mUserRepository.userService()
        }
    }

    val userInfoLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<UserInfo>>>()
    fun userInfo() {
        setRxLifeScope(object : SubscribeViewModel<HttpResponseDataT<UserInfo>>(userInfoLiveData) {
            override fun onSuccess(resp: HttpResponseDataT<UserInfo>) {
                super.onSuccess(resp)
                SPSConstance.userInfo = resp.data
            }
        }) {
            mUserRepository.userInfo()
        }
    }

    val userMineLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<UserMine>>>()
    fun userMine() {
        setRxLifeScope(object : SubscribeViewModel<HttpResponseDataT<UserMine>>(userMineLiveData) {
            override fun onSuccess(resp: HttpResponseDataT<UserMine>) {
                super.onSuccess(resp)
                SPSConstance.userMine = resp.data
            }
        }) {
            mUserRepository.userMine()
        }
    }


    fun userChange(
        face: String? = null, address: String? = null,
        pet_name: String? = null, gender: String? = null,
        qq: String? = null, name: String? = null, idcard: String? = null,
    ) {
        setRxLifeScope(object : SubscribeViewModel<HttpResponseDataT<UserInfo>>(userInfoLiveData) {
            override fun onSuccess(resp: HttpResponseDataT<UserInfo>) {
                super.onSuccess(resp)
                SPSConstance.userInfo = resp.data
            }
        }) {
            mUserRepository.userChange(
                time = httpTime, sign = httpSign1(SPSConstance.uid),
                face = face, address = address, pet_name = pet_name, gender = gender,
                qq = qq, name = name, idcard = idcard
            )
        }
    }

    val userCollectAddLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userCollectAdd(gid: String, type: Int) {
        setRxLifeScope(SubscribeViewModel(userCollectAddLiveData)) {
            mUserRepository.userCollectAdd(
                time = httpTime,
                sign = httpSign1(SPSConstance.uid),
                gid = gid,
                type = type.toString()
            )
        }
    }

    val userCollectDelLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userCollectDel(cid: String, type: Int) {
        setRxLifeScope(SubscribeViewModel(userCollectDelLiveData)) {
            mUserRepository.userCollectDel(
                time = httpTime,
                sign = httpSign1(SPSConstance.uid),
                gid = cid,
                type = type.toString()
            )
        }
    }

    val userGiftGetLiveData = MutableLiveData<HttpResponseBody<WelfareGiftGetResponse>>()
    fun userGiftGet(lid: String, isDraw: Int, position: Int) {
        setRxLifeScope(object : SubscribeViewModel<WelfareGiftGetResponse>(userGiftGetLiveData) {
            override fun onSuccess(resp: WelfareGiftGetResponse) {
                super.onSuccess(resp.apply {
                    this.isDraw = if (isDraw == 0) 1 else 0
                    this.position = position
                })
            }
        }) {
            mUserRepository.userGiftGet(
                time = httpTime, sign = httpSign1(SPSConstance.uid), lid = lid
            )
        }
    }

    val userCouponGetLiveData =
        MutableLiveData<HttpResponseBody<HttpResponseDataT<WelfareCoupon>>>()

    fun userCouponGet(cid: String) {
        setRxLifeScope(SubscribeViewModel(userCouponGetLiveData)) {
            mUserRepository.userCouponGet(cid = cid)
        }
    }

    val userUploadLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<String>>>()
    fun userUpload(fileName: String? = null, images: MutableList<String>) {
        setRxLifeScope(SubscribeViewModel(userUploadLiveData)) {
            mUserRepository.userUpload(fileName, images)
        }
    }

    val userDownloadLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<String>>>()
    fun userDownload(
        urlPath: String, progress: (suspend (ProgressT<String>) -> Unit)? = null,
    ) {
        setRxLifeScope(SubscribeViewModel(userDownloadLiveData)) {
            val destPath =
                StringBuilder(getDiskCacheDirectoryApk(OwnerApplication.application).path)
                    .append("/").append(AppUtils.getAppName()).append(".apk").toString()
            mUserRepository.userDownload(urlPath, destPath, progress)
        }
    }


    val userInviteLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<UserInvite>>>()
    fun userInvite() {
        setRxLifeScope(SubscribeViewModel(userInviteLiveData)) {
            mUserRepository.userInvite(time = httpTime, sign = httpSign1(SPSConstance.uid))
        }
    }

    val userAgreementLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataT<UserAgree>>>()
    fun userAgreement(type: String) {
        setRxLifeScope(SubscribeViewModel(userAgreementLiveData)) {
            mUserRepository.userAgreement(type)
        }
    }


    val userAddressLiveData = MutableLiveData<HttpResponseBody<HttpResponseDataE<UserAddress>>>()
    fun userAddress() {
        setRxLifeScope(SubscribeViewModel(userAddressLiveData)) {
            mUserRepository.userAddress(time = httpTime, sign = httpSign1(SPSConstance.uid))
        }
    }


    val userAddressKeepLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userAddressKeep(
        id: String? = null, consignee: String, mobile: String, uaddress: String, moren: String,
    ) {
        setRxLifeScope(SubscribeViewModel(userAddressKeepLiveData)) {
            mUserRepository.userAddressKeep(id, consignee, mobile, uaddress, moren)
        }
    }


    val userInstallFinishLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userInstallFinish() {
        setRxLifeScope(SubscribeViewModel(userInstallFinishLiveData)) {
            mUserRepository.userInstallFinish(SPSConstance.deviceId)
        }
    }

    val userIsShareLiveData = MutableLiveData<Boolean>()
    fun userShare(activity: Activity, url: String, title: String, desc: String) {

        val web = UMWeb(url).apply {
            this.title = title
            this.description = desc
            this.setThumb(UMImage(activity, R.mipmap.logo_gt))
        }

        ShareAction(activity).withMedia(web).setDisplayList(
            SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE,
            SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE
        ).setCallback(object : UMShareListener {
            override fun onStart(p0: SHARE_MEDIA?) {
                userIsShareLiveData.postValue((true))
            }

            override fun onResult(p0: SHARE_MEDIA?) {
                LogUtils.e("onResult=======${p0}=====")
            }

            override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
                ToastUtils.showShort(p1?.message)
            }

            override fun onCancel(p0: SHARE_MEDIA?) {
                LogUtils.e("onCancel=======${p0}=====")
            }
        }).open()
    }

    fun userPermissions(
        activity: FragmentActivity, consumer: Consumer<Boolean>,
        vararg array: String = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA
//            Manifest.permission.CAMERA,
//            Manifest.permission.RECORD_AUDIO
        ),
    ) {
        val rxPermissions = RxPermissions(activity)
        rxPermissions.request(*array).subscribe { t ->
            consumer.accept(t)
        }
    }

    fun userMatisse(activity: FragmentActivity, maxSelectable: Int = 1) {
        userPermissions(activity, { isPermissions ->
            if (!isPermissions) {
                ToastUtils.showShort("请到设置中开启相关权限")
                return@userPermissions
            }
            Matisse.from(activity)
                .choose(MimeType.ofImage())
                .capture((true))
                .captureStrategy(CaptureStrategy((true), ("com.kzd.gtgame.fileProvider")))
                .countable((true))
                .maxSelectable(maxSelectable)
                .imageEngine(GlideEngine())
                .theme(R.style.Matisse_Zhihu1)
                .forResult((100))
        })
    }

    fun userMatisse(fragment: Fragment, maxSelectable: Int = 1) {
        userPermissions(fragment.requireActivity(), { isPermissions ->
            if (!isPermissions) {
                ToastUtils.showShort("请到设置中开启相关权限")
                return@userPermissions
            }
            Matisse.from(fragment)
                .choose(MimeType.ofImage())
                .capture((true))
                .captureStrategy(CaptureStrategy((true), ("com.kzd.gtgame")))
                .countable((true))
                .maxSelectable(maxSelectable)
                .imageEngine(GlideEngine())
                .theme(R.style.Matisse_Zhihu1)
                .forResult((100))
        })
    }

    val userDiscussIssueLiveData = MutableLiveData<HttpResponseBody<HttpResponseData>>()
    fun userDiscussIssue(
        id: String,
        content: String,
        reply_uid: String? = null,
        pid: String? = null,
        image: String? = null,
    ) {
        setRxLifeScope(SubscribeViewModel(userDiscussIssueLiveData)) {
            mUserRepository.userDiscussIssue(id, content, reply_uid, pid, image)
        }
    }

}